#include "socket.hpp"
#include "protocol.hpp"
#include "NetCal.hpp"
#include <iostream>
#include <memory>

using namespace socket_module;

int main()
{
    // 1. 创建客户端 socket
    std::unique_ptr<Socket> client = std::make_unique<TcpSocket>();
    client->BulidTcpSocket(); // 只需要创建，不绑定端口

    // 2. 设置服务器地址
    InetAddr server("127.0.0.1", 8080); // 修改为你的服务器监听地址和端口
    if (!client->Connect(server, 8080)) {
        std::cerr << "连接服务器失败" << std::endl;
        return 1;
    }

    // 3. 初始化协议对象
    Protocol proto([](Request &req) -> Response {
        return Response(); // 客户端不需要处理，只做接收
    });

    std::cout << "已连接服务器，输入格式：<num1> <op> <num2>，例如：10 + 5" << std::endl;
    std::cout << "输入 exit 退出。" << std::endl;

    while (true)
    {
        std::string line;
        std::cout << ">>> ";
        std::getline(std::cin, line);

        if (line == "exit") break;

        int num1, num2;
        char op;

        std::istringstream iss(line);
        if (!(iss >> num1 >> op >> num2)) {
            std::cerr << "输入格式错误，请重新输入。" << std::endl;
            continue;
        }

        // 构造请求
        Request req(num1, num2, op);
        std::string json_str = req.Serialize();
        std::string send_str = proto.Encode(json_str);

        // 发送
        if (!client->Send(send_str)) {
            std::cerr << "发送失败，连接可能已断开。" << std::endl;
            break;
        }

        // 接收
        std::string buffer;
        while (true)
        {
            int n = client->Recv(&buffer);
            if (n <= 0) {
                std::cerr << "接收失败或连接关闭。" << std::endl;
                goto done; // 跳出主循环
            }

            std::string json_package;
            if (proto.Decode(buffer, &json_package))
            {
                Response resp;
                resp.Deserialize(json_package);
                std::cout << "结果: " << resp.Serialize() << std::endl;
                break;
            }
        }
    }

done:
    client->Close();
    std::cout << "客户端已退出。" << std::endl;
    return 0;
}
